package org.abettor.nookinfo.photo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.abettor.nookinfo.AddressConstant;
import org.abettor.nookinfo.R;
import org.abettor.nookinfo.persist.PhotoHelper;
import org.abettor.nookinfo.view.FileDialog;
import org.abettor.nookinfo.view.ImageViewTouchBase;
import org.abettor.nookinfo.view.OnFileChosenListener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * 显示本地图片
 * 
 * @author shawn
 */
public class PhotoLocalView extends Activity
{
	public static final String PHOTO_ID = "PHOTO_ID";
	private PhotoHelper photoHelper = new PhotoHelper(this);// 图片持久化帮助对象
	private int image;// 当前图片的ID
	private Integer prevImage;
	private Integer nextImage;
	private ImageViewTouch mImageViewTouch;// 用来显示图片得控件
	private Button mReturnButton;
	private ProgressDialog dialog;
	private int loadStatus = 0;// 图片加载状态,-1失败,1成功,2正在加载中
	private ViewGroup mImageFailure;
	private Bitmap mBitmap;// 要显示的图片
	private static final int LOADSUCCESS = 1, LOADING = 2, LOADFAIL = -1;// 加载的状态
	Handler mhandler = new Handler();

	// 是否有下一个图像
	private synchronized boolean hasPreImage()
	{
		return prevImage != null;
	}

	private synchronized boolean hasNxtImage()
	{
		return nextImage != null;
	}

	// 隐藏或者显示加载失败的view
	private void showFailLayout(boolean flag)
	{
		if (flag)
		{
			mImageFailure.setVisibility(View.VISIBLE);
			mImageViewTouch.setVisibility(View.INVISIBLE);
			LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mImageViewTouch.getLayoutParams();
			if (params != null)
			{
				params.height = 0;
				mImageViewTouch.setLayoutParams(params);
			}
			params = (LinearLayout.LayoutParams) mImageFailure.getLayoutParams();
			if (params != null)
			{
				params.height = LinearLayout.LayoutParams.FILL_PARENT;
				mImageFailure.setLayoutParams(params);
			}
		}
		else
		{
			mImageFailure.setVisibility(View.INVISIBLE);
			mImageViewTouch.setVisibility(View.VISIBLE);
			LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mImageViewTouch.getLayoutParams();
			if (params != null)
			{
				params.height = LinearLayout.LayoutParams.FILL_PARENT;
				mImageViewTouch.setLayoutParams(params);
			}
			params = (LinearLayout.LayoutParams) mImageFailure.getLayoutParams();
			if (params != null)
			{
				params.height = 0;
				mImageFailure.setLayoutParams(params);
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.setContentView(R.layout.photo_local_view);
		Bundle extras = getIntent().getExtras();
		image = extras.getInt(PHOTO_ID);
		prevImage = photoHelper.getPrevPhotoById(image);
		nextImage = photoHelper.getNextPhotoById(image);

		mImageFailure = (ViewGroup) findViewById(R.id.photoViewFail);
		mImageViewTouch = (ImageViewTouch) findViewById(R.id.photoView);
		mImageViewTouch.setFocusable(true);
		mImageViewTouch.setLongClickable(true);
		mImageViewTouch.setOnLongClickListener(new OnLongClickListener()
		{
			/**
			 * 保存图片
			 */
			@Override
			public boolean onLongClick(View view)
			{
				ImageViewTouch imageViewer = (ImageViewTouch) view;
				if (imageViewer.isTouchingAndMoving())
				{
					// 如果是移动事件，就忽略此事件
					return false;
				}
				saveImage();
				return false;
			}
		});

		mReturnButton = (Button) findViewById(R.id.photo_view_btn_return);
		mReturnButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				PhotoLocalView.this.finish();
			}
		});
		// 为加载失败的对话加入动画效果
		mImageFailure.setLongClickable(true);
		mImageFailure.setOnTouchListener(new OnTouchListener()
		{
			private boolean ifToastShow = false;// 提示信息是否显示
			private boolean ifLeftMoveOuting = false;// 提示是否在向左移动
			private boolean ifRightMoveOuting = false;// 提示是否在向右移动
			private static final float sMoveOut = 800f;
			// 滑动加载失败的事件
			private GestureDetector.OnGestureListener mImageFailedOnTouchListener = new GestureDetector.SimpleOnGestureListener()
			{
				public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
				{
					float tmpX1 = e1.getX();
					float tmpX2 = e2.getX();
					float width = PhotoLocalView.this.mImageFailure.getWidth() + 20;
					if (tmpX2 - tmpX1 < 0)
					{// 向左滑
						if (PhotoLocalView.this.hasNxtImage())
						{
							if (ifLeftMoveOuting)
							{
								return true;
							}
							ifLeftMoveOuting = true;
							width = -width;
							// 设置动画效果
							Animation translateAnimation = new TranslateAnimation(0, width, 0, 0);
							translateAnimation.setDuration((long) sMoveOut);
							mImageFailure.startAnimation(translateAnimation);
							mhandler.postDelayed(new Runnable()
							{
								@Override
								public void run()
								{
									showFailLayout(false);
									Runnable run = new LoadImageWaitRun(mhandler, PhotoLocalView.this, mImageViewTouch, 1);
									run.run();
								}
							}, (long) sMoveOut);
							// 重新回置
							mhandler.postDelayed(new Runnable()
							{
								@Override
								public void run()
								{
									ifLeftMoveOuting = false;
								}
							}, (long) sMoveOut);
						}
						else
						{
							if (!ifToastShow)
							{
								Toast.makeText(PhotoLocalView.this, getText(R.string.photo_view_toast_no_more_img), Toast.LENGTH_SHORT).show();
								ifToastShow = true;
								mhandler.postDelayed(new Runnable()
								{
									@Override
									public void run()
									{
										ifToastShow = false;
									}
								}, 1000);
								return true;
							}
						}
					}
					else
					{
						if (PhotoLocalView.this.hasPreImage())
						{
							if (ifRightMoveOuting)
							{
								return true;
							}
							ifRightMoveOuting = true;
							// 设置动画效果
							Animation translateAnimation = new TranslateAnimation(0, width, 0, 0);
							translateAnimation.setDuration((long) sMoveOut);
							mImageFailure.startAnimation(translateAnimation);
							mhandler.postDelayed(new Runnable()
							{
								@Override
								public void run()
								{
									showFailLayout(false);
									Runnable run = new LoadImageWaitRun(mhandler, PhotoLocalView.this, mImageViewTouch, -1);
									run.run();
								}
							}, (long) sMoveOut);
							// 重新回置
							mhandler.postDelayed(new Runnable()
							{
								@Override
								public void run()
								{
									ifRightMoveOuting = false;
								}
							}, (long) sMoveOut);
						}
						else
						{
							// 没有对话框,显示提示
							if (!ifToastShow)
							{
								Toast.makeText(PhotoLocalView.this, getText(R.string.photo_view_toast_no_more_img), Toast.LENGTH_SHORT).show();
								ifToastShow = true;
								mhandler.postDelayed(new Runnable()
								{
									@Override
									public void run()
									{
										ifToastShow = false;
									}
								}, 1000);
								return true;
							}
						}
					}
					return true;
				}
			};

			GestureDetector mGestureDetector = new GestureDetector(PhotoLocalView.this, mImageFailedOnTouchListener);

			@Override
			public boolean onTouch(View v, MotionEvent event)
			{
				return mGestureDetector.onTouchEvent(event);
			}
		});
	}

	// 拦截回退的按钮
	@Override
	public void onBackPressed()
	{
		if (mImageViewTouch != null)
		{
			if (mImageViewTouch.getTheScale() > 1.0f)
			{
				mImageViewTouch.zoomTo(1.0f);
				return;
			}
		}
		super.onBackPressed();
	}

	@Override
	public void onResume()
	{
		super.onResume();
		readImage(image);
		Runnable run = new Runnable()
		{
			@Override
			public void run()
			{
				if (loadStatus == PhotoLocalView.LOADING)
				{
					mhandler.postDelayed(this, 50);// 正在加载中,推迟50ms运行
				}
				else if (loadStatus == PhotoLocalView.LOADSUCCESS)
				{
					mImageViewTouch.setImageBitmap(mBitmap);
				}
				else if (loadStatus == PhotoLocalView.LOADFAIL)
				{
					PhotoLocalView.this.showFailLayout(true);
				}
			}
		};
		run.run();
	}

	// 读取特定位置的图像
	private synchronized void readImage(final int image)
	{
		Thread chosenThread = null;
		// 读取本地的图片
		chosenThread = new Thread()
		{
			public void run()
			{
				InputStream is = null;
				try
				{
					// 等待对话框创建完成
					synchronized (this)
					{
						wait();
					}

					final String filepath = AddressConstant.PHOTO_ORIGINAL_IMAGE_LOCAL.replace("ID", image + "");
					File file = new File(filepath);
					if(file.exists())
					{
						PhotoLocalView.this.mBitmap = readBitmap(filepath);
					}
					else
					{
						//	本地文件丢失，显示失败图片
						is = getResources().openRawResource(R.raw.photo_failed);
						PhotoLocalView.this.mBitmap = BitmapFactory.decodeStream(is);
					}
					dialog.dismiss();
					if (PhotoLocalView.this.mBitmap != null)
					{
						// 更新本地数据库
						loadStatus = LOADSUCCESS;
					}
					else
					{
						Log.d(this.getClass().getName(), "Bitmap is null");
						loadStatus = LOADFAIL;
					}
				}
				catch (Exception e)
				{
					Log.d(this.getClass().getName(), "", e);
					dialog.dismiss();
					loadStatus = LOADFAIL;
				}
				finally
				{
					if(is != null)
					{
						try { is.close(); } catch (Exception e) { };
					}
				}
			}
		};
		loadStatus = LOADING;

		// 显示进度对话框
		final Thread theThread = chosenThread;
		dialog = new ProgressDialog(PhotoLocalView.this);
		dialog.setCancelable(true);
		dialog.setTitle(R.string.photo_view_dialog_loading_title);
		dialog.setMessage(getText(R.string.photo_view_dialog_loading_msg));
		dialog.setButton(getText(R.string.photo_view_dialog_loading_btn_cancel), new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// 点击取消按钮，取消操作，同时导致加载失败
				theThread.interrupt();
			}
		});
		theThread.start();
		dialog.show();
		synchronized (theThread)
		{
			theThread.notify();
		}
	}

	// 读取当前图片
	private synchronized boolean loadCurrentImage()
	{
		readImage(image);
		return true;
	}

	// 读取下一张图片
	private synchronized boolean loadNxtImage()
	{
		if (nextImage != null)
		{
			prevImage = image;
			image = nextImage;
			nextImage = photoHelper.getNextPhotoById(image);
		}
		readImage(image);
		return true;
	}

	// 读取上一张
	private synchronized boolean loadPreImage()
	{
		if (prevImage != null)
		{
			nextImage = image;
			image = prevImage;
			prevImage = photoHelper.getPrevPhotoById(image);
		}
		readImage(image);
		return true;
	}

	// 读取二进制文件
	private static Bitmap readBitmap(String path)
	{
		File file = new File(path);
		FileInputStream is = null;
		boolean illeagle = true;// 文件是否合法
		try
		{
			is = new FileInputStream(file);
			Bitmap bitmap = BitmapFactory.decodeStream(is);
			if (bitmap == null)
			{
				illeagle = false;
				Log.d(PhotoLocalView.class.getName(), "Bitmap is null");
			}
			return bitmap;
		}
		catch (Exception e)
		{
			illeagle = false;
			Log.d(PhotoLocalView.class.getName(), "File " + path + " not found...");
			return null;
		}
		finally
		{
			if (is != null)
			{
				try
				{
					is.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			// 文件存在,但是不合法,delete掉
			if (file.exists() && !illeagle)
			{
				file.delete();
			}
		}
	}

	// 更新图片时等待的操作（读取图片时显示一个等待的对话框）
	private static class LoadImageWaitRun implements Runnable
	{
		private Handler handler;
		private PhotoLocalView photoView;
		private ImageViewTouch touch;
		private int type;
		private boolean firstRun = true;

		/**
		 * 构造函数
		 * 
		 * @param handler
		 * @param photoView
		 * @param touch
		 * @param type
		 *            0,当前,-1前一张,1后一张
		 */
		public LoadImageWaitRun(Handler handler, PhotoLocalView photoView, ImageViewTouch touch, int type)
		{
			this.handler = handler;
			this.photoView = photoView;
			this.touch = touch;
			this.type = type;
		}

		@Override
		public void run()
		{
			if (firstRun)
			{// 第一次运行加载图片
				switch (type)
				{
				case 0:
					photoView.loadCurrentImage();
					break;
				case -1:
					photoView.loadPreImage();
					break;
				case 1:
					photoView.loadNxtImage();
					break;
				}
				firstRun = false;
				handler.postDelayed(this, 50);
			}
			else
			{
				if (photoView.loadStatus == PhotoLocalView.LOADING)
				{
					handler.postDelayed(this, 50);// 正在加载中,推迟50ms运行
				}
				else if (photoView.loadStatus == PhotoLocalView.LOADSUCCESS)
				{
					touch.setImageBitmapResetBase(photoView.mBitmap, true);
				}
				else if (photoView.loadStatus == PhotoLocalView.LOADFAIL)
				{
					Toast.makeText(photoView, photoView.getText(R.string.photo_view_load_failed_txt), Toast.LENGTH_SHORT).show();
					photoView.showFailLayout(true);
				}
			}
		}
	}

	public static class ImageViewTouch extends ImageViewTouchBase
	{

		// ///////////////////////////////////////////////////////////////
		private boolean ifToastShow = false;// 提示信息是否显示
		private boolean ifLeftMoveOuting = false;// 提示是否在向左移动
		private boolean ifRightMoveOuting = false;// 提示是否在向右移动
		// ///////////////////////////////////////////////////////////////
		private PhotoLocalView mPhotoView;// 获得父类得引用
		private boolean mEnableTrackballScroll = true;// 是否允许轨迹球
		private static final float sPanRate = 7F;
		private static final float sMoveOut = 800f;
		private boolean touchingAndMoving = false;// 检查是否有是滑动事件
		private float lastCoordinateX = 0F;

		/**
		 * 获得放大的倍数
		 */
		public float getScale()
		{
			return super.getScale();
		}

		/**
		 * 显示原图片大小
		 */
		public void revertSize()
		{
			super.revertSize();
		}

		// 随手指滑动的监听器
		private class MyGestureListener extends GestureDetector.SimpleOnGestureListener
		{
			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
			{
				if (ImageViewTouch.this.getScale() > 1f)
				{
					ImageViewTouch.this.postTranslate(-distanceX, -distanceY);
					ImageViewTouch.this.center(true, true, false);
				}
				else
				{
					float tmpX1 = e1.getX();
					float tmpX2 = e2.getX();
					if (tmpX2 - tmpX1 > 0)
					{
						ImageViewTouch.this.rightMoveOut();
					}
					else
					{
						ImageViewTouch.this.leftMoveOut();
					}
				}
				return true;
			}
		}

		// 增加手势的支持
		GestureDetector mGestureDetector = null;

		public ImageViewTouch(Context context)
		{
			super(context);
			init(context);
		}

		public ImageViewTouch(Context context, AttributeSet attrs)
		{
			super(context, attrs);
			init(context);
		}

		private void init(Context context)
		{
			mPhotoView = (PhotoLocalView) context;
			mGestureDetector = new GestureDetector(context, new MyGestureListener());
			// 加入双击屏幕的监听器
			mGestureDetector.setOnDoubleTapListener(new OnDoubleTapListener()
			{
				@Override
				public boolean onDoubleTap(MotionEvent e)
				{
					if (ImageViewTouch.this.getScale() > 1f)
					{
						ImageViewTouch.this.zoomTo(1.0f);
					}
					else
					{
						ImageViewTouch.this.revertSize();
					}
					return true;
				}

				@Override
				public boolean onDoubleTapEvent(MotionEvent e)
				{
					return false;
				}

				@Override
				public boolean onSingleTapConfirmed(MotionEvent e)
				{
					return false;
				}
			});
		}

		public void setEnableTrackballScroll(boolean enable)
		{
			mEnableTrackballScroll = enable;
		}

		// 进行移位得操作
		protected void postTranslate(float dx, float dy)
		{
			super.postTranslate(dx, dy);
		}

		// 获得图像已经放大的倍数
		public float getTheScale()
		{
			return super.getScale();
		}

		// 向左移出屏幕
		protected void leftMoveOut()
		{
			if (!mPhotoView.hasNxtImage())
			{
				if (!ifToastShow)
				{
					Toast.makeText(mPhotoView, mPhotoView.getText(R.string.photo_view_toast_no_more_img), Toast.LENGTH_SHORT).show();
					ifToastShow = true;
					mHandler.postDelayed(new Runnable()
					{
						@Override
						public void run()
						{
							ifToastShow = false;
						}
					}, 1000);
				}
				return;
			}
			float width = this.getWidth();
			// 加载图片的runnable
			Runnable run = new LoadImageWaitRun(mHandler, mPhotoView, this, 1);
			if (!ifLeftMoveOuting)
			{
				panBy(-(width + 20), 0, sMoveOut);// 开始移动操作
				ifLeftMoveOuting = true;
				// 把左移的状态回退回去
				mHandler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						ifLeftMoveOuting = false;
					}
				}, (long) sMoveOut);
				// 加载下一张图片的操作
				mHandler.postDelayed(run, (long) sMoveOut);
			}
		}

		// 向右移出屏幕
		protected void rightMoveOut()
		{
			if (!mPhotoView.hasPreImage())
			{
				if (!ifToastShow)
				{
					Toast.makeText(mPhotoView, mPhotoView.getText(R.string.photo_view_toast_no_more_img), Toast.LENGTH_SHORT).show();
					ifToastShow = true;
					mHandler.postDelayed(new Runnable()
					{
						@Override
						public void run()
						{
							ifToastShow = false;
						}
					}, 1000);
				}
				return;
			}
			float width = this.getWidth();
			// 加载图片的runnable
			Runnable run = new LoadImageWaitRun(mHandler, mPhotoView, this, -1);
			if (!ifRightMoveOuting)
			{
				panBy(width + 20, 0, sMoveOut);
				ifRightMoveOuting = true;
				mHandler.postDelayed(new Runnable()
				{
					@Override
					public void run()
					{
						ifRightMoveOuting = false;
					}
				}, (long) sMoveOut);
				// 加载上一张图片
				mHandler.postDelayed(run, (long) sMoveOut);
			}
		}

		/**
		 * 放大图像到相应的倍数
		 */
		public void zoomTo(float beishu)
		{
			super.zoomTo(beishu);
		}

		/**
		 * 处理滑动或其他触摸事件，如果是滑动。注意就不应该再触发onLongClick了！
		 */
		@Override
		public boolean onTouchEvent(MotionEvent event)
		{
			mGestureDetector.onTouchEvent(event);
			// 检查一下有没有屏幕滑动事件
			synchronized (this)
			{
				switch (event.getAction())
				{
				case MotionEvent.ACTION_MOVE:
					float x = event.getX();
					if (lastCoordinateX != 0f && Math.abs(lastCoordinateX - x) > 3f)
					{
						// 之所以给出一个范围，是因为手指头太粗，要考虑识别误差
						touchingAndMoving = true;
					}
					lastCoordinateX = x;
					break;
				default:
					lastCoordinateX = 0;
					touchingAndMoving = false;
				}
			}
			return super.onTouchEvent(event);
		}

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event)
		{
			if (!mEnableTrackballScroll)
			{
				if ((keyCode >= KeyEvent.KEYCODE_DPAD_UP) && (keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT))
				{
					return super.onKeyDown(keyCode, event);
				}
			}
			try
			{
				switch (keyCode)
				{
				case KeyEvent.KEYCODE_DPAD_CENTER:
					if (super.getScale() > 1.0f)
					{
						super.zoomTo(1.0f);
					}
					else
					{
						super.revertSize();// 显示原图片的大小
					}
					break;
				case KeyEvent.KEYCODE_DPAD_LEFT:
					if (super.getScale() > 1.0f)
					{
						super.panBy(sPanRate, 0);
					}
					else
					{
						rightMoveOut();
					}
					break;
				case KeyEvent.KEYCODE_DPAD_RIGHT:
					if (super.getScale() > 1.0f)
					{
						panBy(-sPanRate, 0);
					}
					else
					{
						leftMoveOut();
					}
					break;
				case KeyEvent.KEYCODE_DPAD_UP:
					panBy(0, sPanRate);
					break;
				case KeyEvent.KEYCODE_DPAD_DOWN:
					panBy(0, -sPanRate);
					break;
				}
			}
			catch (Exception e)
			{
				Log.d(this.getClass().getName(), "", e);
			}
			return super.onKeyDown(keyCode, event);
		}

		public boolean isTouchingAndMoving()
		{
			boolean flag = false;
			synchronized (this)
			{
				flag = touchingAndMoving;
				lastCoordinateX = 0;
				touchingAndMoving = false;
			}
			return flag;
		}
	}

	// ///////////////////////////////////////////加入删除,和另存的操作///////////////////////////////////
	private final int DEL_IMAG = Menu.FIRST;// 删除的操作
	private final int SAVE_IMAGE = Menu.FIRST + 1;// 另存的操作
	private final int MAG_IMAGE = Menu.FIRST + 2;// 放大的操作
	private final int MIN_IMAGE = Menu.FIRST + 3;// 缩小的操作

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		boolean result = super.onCreateOptionsMenu(menu);
		if (this.mImageViewTouch.getScale() > 1.0f)
		{
			menu.add(0, MAG_IMAGE, 0, R.string.photo_local_view_min).setIcon(R.drawable.photo_menu_zoom_out);
		}
		else
		{
			menu.add(0, MIN_IMAGE, 0, R.string.photo_local_view_mag).setIcon(R.drawable.photo_menu_zoom_in);
		}
		menu.add(0, SAVE_IMAGE, 1, R.string.photo_local_view_save).setIcon(R.drawable.photo_menu_save);
		menu.add(0, DEL_IMAG, 2, R.string.photo_local_view_del).setIcon(R.drawable.photo_menu_remove);
		return result;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		if (this.mImageViewTouch.getScale() <= 1.0f)
		{
			menu.removeItem(MIN_IMAGE);
			if (menu.findItem(MAG_IMAGE) == null)
			{
				menu.add(0, MAG_IMAGE, 0, R.string.photo_local_view_mag).setIcon(R.drawable.photo_menu_zoom_in);
			}
		}
		else
		{
			menu.removeItem(MAG_IMAGE);
			if (menu.findItem(MIN_IMAGE) == null)
			{
				menu.add(0, MIN_IMAGE, 0, R.string.photo_local_view_min).setIcon(R.drawable.photo_menu_zoom_out);
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}

	/**
	 * 系统菜单执行的操作
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
		case DEL_IMAG:
			delImage();
			break;
		case SAVE_IMAGE:
			saveImage();
			break;
		case MAG_IMAGE:
			zoomInImage();
			break;
		case MIN_IMAGE:
			zoomOutImage();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	// 删除图片的操作
	private void delImage()
	{
		Bundle extras = new Bundle();
		Intent viewImageIntent = new Intent();
		viewImageIntent.setClass(this, PhotoLocalView.class);
		if (this.hasNxtImage())
		{
			extras.putInt(PhotoLocalView.PHOTO_ID, nextImage);
			viewImageIntent.putExtras(extras);
			this.startActivity(viewImageIntent);
		}
		else if (this.hasPreImage())
		{
			extras.putInt(PhotoLocalView.PHOTO_ID, prevImage);
			viewImageIntent.putExtras(extras);
			this.startActivity(viewImageIntent);
		}
		photoHelper.removePhoto(image);
		this.finish();
	}

	// 放大图片的操作
	private void zoomInImage()
	{
		mImageViewTouch.revertSize();
	}

	// 缩小图片的操作
	private void zoomOutImage()
	{
		mImageViewTouch.zoomTo(1.0f);
	}

	// 另存图片的操作
	private void saveImage()
	{
		if (loadStatus != PhotoLocalView.LOADSUCCESS)
		{
			return;
		}
		final Bitmap bitmap = mImageViewTouch.getBitmap();
		if (bitmap == null)
		{
			Log.d(this.getClass().getName(), "Bitmap is null...");
			return;
		}

		FileDialog dialog = new FileDialog(PhotoLocalView.this, FileDialog.FileType.file);
		dialog.setTitle(R.string.photo_view_dialog_save_title);
		dialog.setOnFileChosenListener(new OnFileChosenListener()
		{
			@Override
			public void onFileChosen(FileDialog dialog)
			{
				// 保存文本文件
				final File file = dialog.getFile();
				if (file == null)
				{
					return;
				}

				if (file.exists())
				{
					// 是否要覆盖文件
					Builder builder = new Builder(PhotoLocalView.this);
					builder.setTitle(R.string.photo_view_dialog_save_overwrite_title);
					builder.setMessage(R.string.photo_view_dialog_save_overwrite_content);
					builder.setPositiveButton(R.string.photo_dialog_view_save_overwrite_btn_ok, new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialoginterface, int i)
						{
							OutputStream os = null;
							try
							{
								file.delete();
								file.createNewFile();
								os = new FileOutputStream(file);
								bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
							}
							catch (Exception e)
							{
								Log.d(this.getClass().getName(), "", e);
							}
							finally
							{
								if (os != null)
								{
									try { os.close(); } catch (Exception e) { };
								}
							}
							dialoginterface.dismiss();
						}
					});
					builder.setNegativeButton(R.string.photo_view_dialog_save_overwrite_btn_cancel, new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.dismiss();
						}
					});
					builder.show();
				}
				else
				{
					OutputStream os = null;
					try
					{
						file.createNewFile();
						os = new FileOutputStream(file);
						bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
					}
					catch (Exception e)
					{
						Log.d(this.getClass().getName(), "", e);
					}
					finally
					{
						if (os != null)
						{
							try { os.close(); } catch (Exception e) { };
						}
					}
				}
			}
		});
		dialog.show();
	}
}
